import './index.scss';
import React, { useEffect, useState, useRef } from "react";
import { Dropdown, Radio, Space, Button, Popup, Empty } from 'antd-mobile'
import { DeleteOutline } from 'antd-mobile-icons'
import { Tabs } from 'antd-mobile'
import { chainsall, user_wallet_list, user_wallet_info, user_order_list, user_submit_order, token_usd_price, user_remove_token } from '@/utils/mixin.ts'
import { Checkbox, Form, Input, message, Spin, Switch } from 'antd';
import { useNavigate } from 'react-router-dom';
import DropdownRef from 'antd-mobile/es/components/dropdown';
import send from '@/assets/photos/send-button.png';
import receive from '@/assets/photos/receive-button.png';
import charge from '@/assets/photos/charge-button.png';
import purchase from '@/assets/photos/purchase-button.png';
import { SetOutline } from 'antd-mobile-icons';
import add_import_btn from '@/assets/new/add_import_btn.png';
import profitLoss from '@/assets/new/profit-loss.png';
import refreshButton from '@/assets/new/refresh-button.png'
import { useTranslation } from 'react-i18next';
import BNB from '@/assets/new/BNB.png'
import ETH from '@/assets/new/ETH.png'
import MATIC from '@/assets/new/MATIC.png'
import set from '@/assets/new/set.png'
import del from '@/assets/new/del.png'
import pro from '@/assets/new/pro.png'
import ImportToken from '@/pages/bot/importToken'
const EthBot = () => {

  const { t } = useTranslation();
  const [currency, setCurrency] = useState([]);
  const [wallet, setWallet] = useState([]);
  const [info, setInfo] = useState({});
  const [ActWallet, setActWallet] = useState({ wallet_id: '', name: '' })
  const [ActCurrency, setActCurrency] = useState({ keyNode: '', name: '', symbol: '' })
  const [Orders, setOrders] = useState([])
  const [status, setStatus] = useState('success')
  const [type, setType] = useState('')
  const [visible2, setVisible2] = useState(false)
  const [popId, setPopId] = useState(0)
  const [token_address, set_token_address] = useState(null)
  const ref = useRef(DropdownRef)
  const navigate = useNavigate();
  const [spinning, setSpinning] = React.useState(false);
  const [token_price, set_token_price] = useState('')
  const [eth_amount, set_eth_amount] = useState('')
 
  const [usd_price, set_usd_price] = useState('')
  const [SwitchPro, setSwitchPro] = useState(false)
  // const [token_price, set_token_price] = useState('')
  const [callback_ratio, set_callback_ratio] = useState('')
  const [importShow, setImportShow] = useState(false)
  const tabList = [
    {
      name: t('Instant Deal'),
      value: 'market_order',
    },
    {
      name: t('Stop profit trading'),
      value: 'profit_sell',
    },
    {
      name: t('BUY LIMIT'),
      value: 'limit_buy',
    },
  ];
  const buyNav = [
    {
      name: t('Return profit and stop loss'),
      id: 0
    },
    // {
    //   name: t('BUY LIMIT'),
    //   id: 1
    // }
  ]
  const getAll = async () => {
    let list = [];
    const res = await chainsall();

    for (let key in res.data.networks) {
      list.push(Object.assign({}, { ...res.data.networks[key] }, { keyNode: key }));
    }

    setCurrency(() => {
      const updatedCurrency = [...list];
        setActCurrency({
          keyNode: updatedCurrency[1].keyNode,
          name: updatedCurrency[1].name,
          symbol: updatedCurrency[1].symbol
        })
     
      return updatedCurrency;
    });

  }

  const get_user_wallet_list = async () => {
    const res = await user_wallet_list({
      email: localStorage.getItem('email'),
      network: ActCurrency.keyNode
    })
    setWallet(() => {
      const updatedCurrency = res.data && [...res.data];
      if (res.data.length > 0) {
        setActWallet({
          name: updatedCurrency[0].name,
          wallet_id: updatedCurrency[0].wallet_id
        })
        localStorage.setItem('wallet_id', updatedCurrency[0].wallet_id);
      }
      return updatedCurrency
    })
  }

  const toNavigate = (nav) => {
    localStorage.setItem('detail', JSON.stringify({...ActCurrency, ...ActWallet, ...info}))
    switch (nav) {
      default : navigate(nav)
    }
  }


  const get_user_wallet_info = async () => {
    console.log(ActCurrency)
    const res = await user_wallet_info({
      email: localStorage.getItem('email'),
      network: ActCurrency.keyNode,
      wallet_id: ActWallet.wallet_id,
     
    })
    console.log(res)
    res.data && res.data.length && setInfo(() => {
      const data = res.data[0]
      return data
    })
    // setInfo()
  }

  const tabSymbol = (item) => {
    setActCurrency(item)
    localStorage.setItem('keyNode', item.keyNode)
    
    ref.current?.close()
  }

  const tabWallet = (item) => {
    setActWallet(item)
    localStorage.setItem('wallet_id', item.wallet_id)
    ref.current?.close()
  }

  const onChange = (key) => {
    console.log(key);
    setOrders([])
    if(key == 'all') {
      setType('market_order')
    } else {
      setType('')
    }
    setStatus(key)
  }

  const get_user_order_list = () => {
    setSpinning(true);
    user_order_list({
      email: localStorage.getItem('email'),
      network: ActCurrency.keyNode,
      wallet_id: ActWallet.wallet_id,
      status,
      type,
      page: 1,
      size: 100

    }).then(res => {
      console.log(res)
      setOrders(res.data)
      setSpinning(false);
    }).catch(err => {
      setSpinning(false);
    })
  } 

  useEffect(() => {
    console.log(process.env)
    let pro = localStorage.getItem('checked')
    pro && setSwitchPro(JSON.parse(pro))
    const fetchData = async () => {
      await getAll();
      // 在这里 ActCurrency 已经更新，可以访问 symbol
      console.log('ActCurrency.symbol:', ActCurrency.symbol);
    };
    fetchData();
  }, []);  // 空数组表示只在组件挂载时执行

  useEffect(() => {
    get_user_order_list();
  }, [type]);

  useEffect(() => {
    get_user_order_list();
  }, [status]);

  useEffect(() => {
    get_user_wallet_list();
  }, [ActCurrency]);

  useEffect(() => {
    get_user_wallet_info();
    get_user_order_list()
  }, [ActWallet]);

  const txtDis = (str) => {
    if(!str) return
    const firstFour = str.slice(0, 4);
    const lastFour = str.slice(-4);
    const maskedString = `${firstFour}****${lastFour}`;
    return maskedString;
  };

  const sell = (val) => {
    setSpinning(true);
    user_submit_order({
      network: ActCurrency.keyNode,
      email: localStorage.getItem('email'),
      wallet_id: ActWallet.wallet_id,
      type: "sell",
      // sell_ratio: 1,
      // pool_address: "",
      // pool_version: "",
      ...val
    }).then(res => {
      setSpinning(false);
      if(res.code == 0) {
        message.success(t('Successfully sold'))
      } else {
        message.error(res.msg)
      }
      get_user_order_list()
    })
  }

  const cancel = (id) => {
    setSpinning(true);
    user_submit_order({
      network: ActCurrency.keyNode,
      email: localStorage.getItem('email'),
      order_id: id,
      wallet_id: ActWallet.wallet_id,
      type: "cancel"
    }).then(res => {
      setSpinning(false);
      if(res.code == 0) {
        message.success(t('Revoke successful'))
      } else {
        message.error(res.msg)
      }
      get_user_order_list()
    })
  }

  const tabAll = (val) => {
    setType(val.value)
  }

  const formatDateString = (inputDateString) => {
    if(!inputDateString) return
    const inputDate = new Date(inputDateString);

  const options = {
    month: "short",
    day: "numeric",
    hour: "numeric",
    minute: "numeric",
    second: "numeric",
  };

  const formatter = new Intl.DateTimeFormat("en-US", options);
  return formatter.format(inputDate);
  }

  const truncateToTwoDecimals = (number) => {
    if(!number) return
    return Math.floor(number * 100) / 100;
  }

  const open = (val) => {
    if(!val) return
    window.open('https://bscscan.com/tx/' + val)
  }

  const switchStatus = (val) => {
    let str = ''
    switch (val) {
      case 'pending':
         str = t('pending')
         break;
         case 'cancelled':
          str = t('Cancel')
          break;
          case 'success':
         str = t('success')
         break;
    }

    return str
    
  }

  const TokenAdd = () => {
    // navigate('/dashboard/importToken')
    // localStorage.setItem('detail', JSON.stringify({...ActWallet, ...ActCurrency, ...info}))
    localStorage.setItem('keyNode', ActCurrency.keyNode)
    localStorage.setItem('wallet_id', ActWallet.wallet_id)
    setImportShow(true)
  }

  const get_token_usd_price = (val) => {
    setSpinning(true);
    set_token_address(val)
    token_usd_price({
      token_address :val.token_address,
      network: val.chain
    }).then(res => {
      if(res.code == 0) {
        setVisible2(true)
        set_usd_price(res.data)
      }else {
        message.error(res.msg)
      }
      setSpinning(false);
    })
  }

  const submitPop = () => {
    switch(popId) {
      case 0:
        if(callback_ratio*1 <= 0) {
          return message.error(t('请输入正确的数值'))
        }
        setSpinning(true);
        setVisible2(false)
        user_submit_order({
          network: token_address.chain,
          type: "profit_sell",
          ...token_address,
          callback_ratio: callback_ratio / 100
        }).then(res => {
          if(res.code == 0) {
            message.success(t('Operation successful'))
            get_user_order_list()
          } else if (res.msg == 'insufficient_tokens'){
            message.error(t('balance'))
          } else {
            message.error(res.msg)
          }
          setSpinning(false);
          set_callback_ratio('')
        })
        break;
      case 1:
        setSpinning(true);
        setVisible2(false)
        user_submit_order({
          network: token_address.chain,
          type: "limit_buy",
          ...token_address,
          token_price,
          eth_amount
        }).then(res => {
          if(res.code == 0) {
            message.success(t('Operation successful'))
            get_user_order_list()
          } else if (res.msg == 'insufficient_funds'){
            message.error(t('balance'))
          }else {
            message.error(res.msg)
          }
          setSpinning(false);
          set_token_price('')
          set_eth_amount('')
        })
        break;
    }
  }

  const tabPop = (val) => {
    setPopId(val.id)
  }

  const deleteSymbol = (val) => {
    setSpinning(true);
      user_remove_token({
          network: val.chain,
          email: localStorage.getItem('email'),
          wallet_id: val.wallet_id,
          token_address: val.token_address
        }).then(res => {
          if(res.code == 0) {
            message.success(t('Operation successful'))
            get_user_order_list()
          } else {
            message.error(res.msg)
          }
          setSpinning(false);
        })
  }

  const switchImg = (val) => {
    let icon = ''
    switch (ActCurrency.symbol) {
      case 'BNB':
        icon = BNB
      break;
      case 'ETH':
        icon = ETH
      break;
      case 'MATIC':
        icon = MATIC
      break;
    }
    return icon
  }

  const onChangSwitch = (checked) => {
    console.log(checked);
    localStorage.setItem('checked', checked)
    setSwitchPro(checked)
  };

  const BuySell = (val) => {
    localStorage.setItem('token_address', JSON.stringify(val))
    localStorage.setItem('detail', JSON.stringify({...ActWallet, ...ActCurrency, ...info}))
    navigate('/dashboard/trade')
  }

  const handleImportTokenCallback = (data) => {
    // 处理回调函数中的逻辑
    console.log('Received data:', data);

    // 关闭 ImportToken 组件
    setImportShow(false);
  };

  return (
    <div className='ethBot'>
      <Popup
              className='popup-ethbot'
              visible={visible2}
              showCloseButton
              
              onMaskClick={() => {
                setVisible2(false)
              }}
              onClose={() => {
                setVisible2(false)
              }}
              position='top'
              bodyStyle={{ height: '40vh' }}
            >
              <div className='title-pop'>
              Stop profit
              </div>
              <div className='but'>
                {
                  buyNav.map(res => {
                    return  <Button onClick={() => {tabPop(res)}} color={popId == res.id ? 'warning' : 'primary'}>{res.name}</Button>
                  })
                }
              </div>

              {!popId ? <div className='input-pop'>
              <Input value={callback_ratio} onChange={(e) => {set_callback_ratio(e.target.value)}}  suffix="%" />
              </div>
              :
              <div className='limit-pop'>
                <div className='all-pop'>
                {usd_price && usd_price} {token_address && token_address.token_name}
                </div>
                <div className='inp-pop'>
                <Input value={token_price} onChange={(e) => { set_token_price(e.target.value) }} prefix="买入价格："  />
                <Input value={eth_amount} onChange={(e) => { set_eth_amount(e.target.value) }}  prefix="买入数量："  />
                </div>
                <p>
                 {ActCurrency.symbol} 余额：{info && info.balance}
                </p>
              </div>}
              <div className='submit-pop'>
              <Button block color='primary' onClick={() => submitPop()} style={{color: 'white'}} size='large'>
                提交
              </Button>
              </div>
            </Popup>
      <Spin spinning={spinning} fullscreen />
      <div className='operate'>
        <Dropdown ref={ref}>
          
          <Dropdown.Item key='sorter' title={ActCurrency.symbol}>
          <div className='tit'>选择网络</div>
            <div className='ul'>
              {
                currency.map(item => {
                  return <li className={item.keyNode == ActCurrency.keyNode ? 'active li' : 'li'} onClick={() => { tabSymbol(item) }}>
                    {item.keyNode == ActCurrency.keyNode && <span></span>}
                    <p> <span>{item.name.slice(0, 1)}</span> {item.name}</p>
                  </li>
                })
              }
            </div>
          </Dropdown.Item>
          <Dropdown.Item key='bizop' title={ActWallet.name}>
          <div className='tit'>选择钱包</div>
            <div className='ul'>
              {
                wallet.map(item => {
                  return <li className={item.wallet_id == ActWallet.wallet_id ? 'active li' : 'li'} onClick={() => { tabWallet(item) }}>
                    {item.wallet_id == ActWallet.wallet_id && <span></span>}
                    <p>{item.name}</p>
                  </li>
                })
              }
            </div>
          </Dropdown.Item>
          <div className='font'>
             <img src={set} onClick={() => {toNavigate('/dashboard/settings')}} />
              {/* <SetOutline /> */}
          </div>
        </Dropdown>
        {!importShow && <div className='content'>
          <div class="title">
            <div class="cnum address-line">
              <span class="cnumv short-address">{txtDis(info.address)}</span>
            </div>
            <div class="num wallet-number">
              <span class="numv wallet-balance">{info.balance}</span>
              <span class="newk wallet-type">{ActCurrency.symbol}</span>
            </div>
            <div class="usd wallet-wealth">
              &nbsp;$
              <span class="usdv wallet-wealth">{info.balance_usd}</span>
            </div>
          </div>
          <div className='options'>
            <div class="option-button" id="sendBtn" onClick={() => { toNavigate('/dashboard/transfer') }}>
              <img src={send} alt="" /> <span data-lang="SEND">{t('send')}</span>
            </div>
            <div class="option-button" id="receiveBtn" onClick={() => { toNavigate('/dashboard/walletsdetail') }}>
              <img src={receive} alt="" />
              <span data-lang="Receive">{t('Receive')}</span></div>
            <div class="option-button" id="Community" >
              <img src={charge} alt="" onClick={() => { toNavigate('/dashboard/vip') }} />
              <span data-lang="Community" >VIP </span>
            </div>
            <div class="option-button" id="purchaseBtn" onClick={() => { toNavigate('/dashboard/nftbuy')  }}>
              <img src={purchase} alt="" />
              <span data-lang="NFT">NFT</span></div>
          </div>
        </div>}
      </div>
      {!importShow && <div className='tab'>
          <Tabs onChange={onChange} defaultActiveKey='success' >
            <Tabs.Tab title={t('Position')} key='success'>
            <div className='order-nav'>
                <p onClick={() => {TokenAdd()}}>{t('property')} <img  src={add_import_btn}/></p>
                <div className='pro'>
                <Switch checked={SwitchPro} onChange={onChangSwitch} />
                  <img src={pro} />
                </div>
                <p onClick={() => {get_user_order_list()}}><img  src={refreshButton}/> {t('Refresh')} </p>
              </div>
            <div className='ul-pendings'>
                { Orders && !!Orders.length ? Orders.map(val => {
                  return <li>
                    <img src={switchImg(val)} />
                  <div className='name-pend'>
                    <p>{val.token_name}</p>
                    <span>{val.token_quantity}</span>
                  </div>
                  <div className='order-option'>
                  {val.token_address != '0x0000000000000000000000000000000000000000' && val.token_name !== 'USDT' ? <img onClick={() => {get_token_usd_price(val)}} src={profitLoss}/> : <img className='nbsp' />}
                  {val.token_address != '0x0000000000000000000000000000000000000000' && val.token_name !== 'USDT' ?  <Button color='warning' fill='solid' onClick={() => {
                    // sell(val)
                    BuySell(val)
                  }}>
                    {t('交易')}
                  </Button> : <Button className='nbsp'></Button>}
                  {val.token_name !== 'BNB' && val.token_name !== 'USDT' ? <img src={del} className='del'  onClick={() => deleteSymbol(val)}/> : <DeleteOutline className='nbsp' />}
                  </div>
                 
                </li>
                }): <Empty style={{marginTop: 50}} /> 
              }
              </div>
            </Tabs.Tab>
            <Tabs.Tab title={t('Processing')} key='pending'>
              <div className='order-nav'>
                <p>{t('order')}</p>
                <p onClick={() => {get_user_order_list()}}><img  src={refreshButton}/> {t('Refresh')} </p>
              </div>
              <div className='ul-pendings'>
                { Orders && !!Orders.length ? Orders.map(val => {
                  return <li>
                    <img src={switchImg(val)} />
                  <div className='name-pend'>
                    <p>{val.token_name}</p>
                    <span>{val.token_quantity}</span>
                  </div>
                  <div>
                    <Button color='primary' fill='outline' onClick={() => {
                      cancel(val.id)
                    }}>
                      {t('Cancel')}
                    </Button>
                  </div>
                 
                </li>
                }) : <Empty style={{marginTop: 50}}/> 
              } 
              </div>
            </Tabs.Tab>
            <Tabs.Tab title={t('transaction')} key='all'>
              <div className='all-tab'>
                {
                  tabList.map(val => {
                    return <div className={type == val.value ? 'li act': 'li'} onClick={() => tabAll(val)}>
                      {val.name}
                    </div>
                  })
                }
              </div>
              <div className='allList'>
                {
                   Orders && !!Orders.length ? Orders.map(item => {
                    return <div className='li'>
                      <span style={{color: item.status == 'success' ? 'rgba(32, 122, 5, 1)' : item.status == 'pending' ? 'rgba(0, 255, 0, 1)' : '' }}>{switchStatus(item.status)}</span>
                      <div className='symbol'>
                        <p>{truncateToTwoDecimals(item.token_quantity)} {item.token_name}</p>
                        <span>${truncateToTwoDecimals(item.trade_value_usd)} USD</span>
                      </div>
                      <div className='address'>
                        <p onClick={() => {open(item.txhash)}}>{item.txhash ? txtDis(item.txhash) : '----'}</p>
                        <span>{formatDateString(item.create_time)}</span>
                      </div> 
                </div>
                  }) : <Empty style={{marginTop: 50}}/> 
                }
              </div>
            </Tabs.Tab>
        </Tabs>
          
        </div>}
       {importShow && <ImportToken onCallback={handleImportTokenCallback} />}
    </div>
  );
};

export default EthBot;
